﻿using System;
using System.Collections.Generic;
using System.Linq;
using MoroMoro.Samples.ToDoList.Base.Application;
using MoroMoro.Samples.ToDoList.Base.Domain.Specifications;
using MoroMoro.Samples.ToDoList.Application;
using MoroMoro.Samples.ToDoList.Application.Categories;
using MoroMoro.Samples.ToDoList.Application.ToDos;
using MoroMoro.Samples.ToDoList.Domain.Categories;
using MoroMoro.Samples.ToDoList.Domain.ToDos;
using MoroMoro.Samples.ToDoList.Presentation.ErrorMessages.Categories;
using MoroMoro.Samples.ToDoList.Presentation.ErrorMessages.ToDos;
using MoroMoro.Samples.ToDoList.Presentation.Models.ToDos;
using MoroMoro.Samples.ToDoList.Presentation.Utils;
using MoroMoro.Samples.ToDoList.Presentation.Views;

namespace MoroMoro.Samples.ToDoList.Presentation.Presenters
{
    /// <summary>
    /// ToDoList プレゼンターです。
    /// </summary>
    public sealed partial class ToDoListPresenter : Presenter<IToDoListView>
    {
        /// <summary>
        /// <see cref="ToDoListPresenter"/> クラスの新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="view">ビュー。</param>
        /// <param name="facade">ファサード。</param>
        /// <exception cref="System.ArgumentNullException">view または facade が null です。</exception>
        public ToDoListPresenter(IToDoListView view, ToDoListFacade facade)
            : base(view)
        {
            if (facade == null)
            {
                throw new ArgumentNullException("facade");
            }
            _facade = facade;
            _isOperatingByPresenter = false;
        }


        /// <summary>
        /// ファサード。
        /// </summary>
        private readonly ToDoListFacade _facade;

        /// <summary>
        /// プレゼンタによってビューが操作されているかどうかを示す値。
        /// </summary>
        private bool _isOperatingByPresenter;


        /// <inheritdoc/>
        protected override void RegisterEventHandlers()
        {
            base.RegisterEventHandlers();

            _facade.Refreshed += OnFacadeRefreshed;
            _facade.ToDoListLoadError += OnFacadeToDoListLoadError;
            _facade.CategoryListLoadError += OnFacadeCategoryListLoadError;

            View.StateComboBoxSelectedIndexChanged += OnStateComboBoxSelectedIndexChanged;
            View.CategoryComboBoxSelectedIndexChanged += OnCategoryComboBoxSelectedIndexChanged;

            View.CreationButtonClick += OnCreationButtonClick;
            View.EditionButtonClick += OnEditionButtonClick;
            View.DeletionButtonClick += OnDeletionButtonClick;

            View.ForwadToTouchedButtonClick += OnForwadToTouchedButtonClick;
            View.ForwadToCompletedButtonClick += OnForwadToCompletedButtonClick;
            View.ReversionToUntouchedButtonClick += OnReversionToUntouchedButtonClick;
            View.ReversionToTouchedButtonClick += OnReversionToTouchedButtonClick;

            View.CategoryCreationButtonClick += OnCategoryCreationButtonClick;
            View.CategoryEditionButtonClick += OnCategoryEditonButtonClick;
            View.CategoryDeletionButtonClick += OnCategoryDeletionButtonClick;
        }

        /// <summary>
        /// <see cref="ToDoListFacade.Refreshed"/> イベントを処理します。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnFacadeRefreshed(object sender, EventArgs e)
        {
            _isOperatingByPresenter = true;
            try
            {
                View.ClearItems();
                View.ShowItems(_facade.ToDoList);

                BindStateFilters();
                View.SelectedStateFilter = _facade.StateFilter;

                BindCategories();
                View.SelectedCategory = _facade.CategoryFilter;
            }
            finally
            {
                _isOperatingByPresenter = false;
            }
        }

        /// <summary>
        /// 状態フィルターをバインドします。
        /// </summary>
        private void BindStateFilters()
        {
            var stateCaptions = new ComboBoxDataSource<ToDoState?>();
            stateCaptions.Add(null, "指定なし");
            stateCaptions.AddRange(ToDoExtension.StateDictionary, item => (ToDoState?)item);
            View.BindStateFilter(stateCaptions, "Value", "Text");
        }

        /// <summary>
        /// カテゴリフィルターをバインドします。
        /// </summary>
        private void BindCategories()
        {
            var categoryCaptions = new ComboBoxDataSource<Category>();
            categoryCaptions.Add(null, "未分類");
            categoryCaptions.AddRange(_facade.CategoryList, item => item.Name);
            View.BindCategories(categoryCaptions, "Value", "Text");
        }

        /// <summary>
        /// <see cref="ToDoListFacade.ToDoListLoadError"/> イベントを処理します。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnFacadeToDoListLoadError(object sender, ErrorEventArgs<ToDoListLoadErrors> e)
        {
            var errorMessage = new ToDoListLoadErrorMessage();
            e.Errors.HandledBy(errorMessage);
            View.ShowErrorMessageBox(errorMessage);
        }

        /// <summary>
        /// <see cref="ToDoListFacade.CategoryListLoadError"/> イベントを処理します。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnFacadeCategoryListLoadError(object sender, ErrorEventArgs<CategoryListLoadErrors> e)
        {
            var errorMessage = new CategoryListLoadErrorMessage();
            e.Errors.HandledBy(errorMessage);
            View.ShowErrorMessageBox(errorMessage);
        }


        /// <inheritdoc/>
        protected override void OnLoad(object sender, EventArgs e)
        {
            base.OnLoad(sender, e);

            _facade.Initialize();
        }

        /// <summary>
        /// 状態フィルタが変更された時の処理を行います。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnStateComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (_isOperatingByPresenter)
            {
                return;
            }
            _facade.ChangeToDoStateFilter(View.SelectedStateFilter);
        }

        /// <summary>
        /// カテゴリフィルタが変更された時の処理を行います。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCategoryComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (_isOperatingByPresenter)
            {
                return;
            }
            _facade.ChangeCategoryFilter(View.SelectedCategory);
        }
    }
}
